<template>
  <div class="min-h-screen bg-gray-50 pb-safe">
    <!-- 导航栏 -->
    <van-nav-bar
      title="用户详情"
      left-text="返回"
      left-arrow
      @click-left="router.back()"
      fixed
      placeholder
    />

    <div class="px-4" v-if="userInfo">
      <!-- 个人资料 -->
      <van-cell-group inset title="个人资料" class="mt-3">
        <van-cell title="姓名" :value="userInfo.name" />
        <van-cell title="性别" :value="userInfo.gender" />
        <van-cell title="婚姻状况" :value="userInfo.marital_status_desc" />
        <van-cell title="出生年份" :value="userInfo.birth_year" />
        <van-cell title="户籍地" :value="userInfo.hometown" />
        <van-cell 
          title="联系方式" 
          :value="maskedContact"
          is-link
          @click="handleContactClick"
        />
        <van-cell title="工作地点" :value="userInfo.work_location" />
        <van-cell title="学历" :value="userInfo.education" />
      </van-cell-group>

      <!-- 个人详情 -->
      <van-cell-group inset title="个人详情" class="mt-3">
        <van-cell title="身高" :value="userInfo.height + 'cm'" />
        <van-cell title="体重" :value="userInfo.weight ? userInfo.weight + 'kg' : '未填写'" />
        <van-cell title="星座" :value="userInfo.zodiac" />
        <van-cell title="职业" :value="userInfo.occupation" />
        <van-cell title="月收入" :value="userInfo.income" />
        <van-cell title="家庭成员" :value="userInfo.family" />
        <van-cell title="住房情况" :value="userInfo.housing" />
        <van-cell title="是否有车" :value="userInfo.car" />
        <van-cell title="兴趣爱好" :value="userInfo.hobbies" />
        <van-cell title="性格特点" :value="userInfo.personality" />
        <van-cell title="自我介绍" :value="userInfo.introduction" />
        <van-cell v-if="userInfo.photo_urls?.length" title="照片">
          <template #value>
            <div class="photo-grid">
              <div v-for="(photo, index) in userInfo.photo_urls" :key="index" class="photo-item">
                <van-image
                  :src="photo"
                  fit="cover"
                  @click="previewImage(index)"
                />
              </div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 择偶意向 -->
      <van-cell-group inset title="择偶意向" class="mt-3 mb-20">
        <van-cell title="接受离异" :value="userInfo.accept_divorced" />
        <van-cell title="择偶要求" :value="userInfo.requirements" />
      </van-cell-group>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="flex items-center justify-center min-h-[300px] md:min-h-[400px]">
      <van-loading type="spinner" color="#1989fa" />
    </div>

    <!-- 错误状态 -->
    <div v-else class="flex flex-col items-center justify-center min-h-[300px] md:min-h-[400px]">
      <van-empty description="获取用户信息失败" />
      <van-button class="mt-4" @click="fetchUserInfo">重新加载</van-button>
    </div>

    <!-- 数字键盘 -->
    <van-number-keyboard
      v-model="password"
      :show="showKeyboard"
      :maxlength="4"
      @blur="showKeyboard = false"
      @input="onInput"
      @delete="onDelete"
    />

    <!-- 密码输入弹窗 -->
    <van-popup v-model:show="showKeyboard" position="bottom" :style="{ height: '40%' }">
      <div class="p-4">
        <div class="text-center mb-4">请输入4位数字密码</div>
        <div class="flex justify-center mb-4">
          <div class="grid grid-cols-4 gap-2">
            <div v-for="i in 4" :key="i" class="w-10 h-10 border rounded flex items-center justify-center">
              {{ password.length >= i ? '●' : '' }}
            </div>
          </div>
        </div>
      </div>
      <van-number-keyboard
        :show="true"
        @input="onInput"
        @delete="onDelete"
        :maxlength="4"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showImagePreview, showToast } from 'vant'
import request from '@/utils/request'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const userInfo = ref(null)
const showContact = ref(false)
const password = ref('')
const showKeyboard = ref(false)
const isVerified = ref(localStorage.getItem('listVerified') === 'true')

// 处理联系方式显示
const maskedContact = computed(() => {
  if (!userInfo.value?.contact) return ''
  if (showContact.value) return userInfo.value.contact
  return userInfo.value.contact.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
})

// 切换联系方式显示
const handleContactClick = () => {
  if (!isVerified.value) {
    showKeyboard.value = true
    return
  }
}

// 处理输入
const onInput = (key) => {
  if (password.value.length < 4) {
    password.value += key
    if (password.value.length === 4) {
      if (password.value === '9303') {
        isVerified.value = true
        localStorage.setItem('listVerified', 'true')
        showKeyboard.value = false
      } else {
        showToast('密码错误')
        password.value = ''
      }
    }
  }
}

// 处理删除
const onDelete = () => {
  if (password.value.length > 0) {
    password.value = password.value.slice(0, -1)
  }
}

// 添加处理图片 URL 的函数
const getFullImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${import.meta.env.VITE_UPLOAD_URL}${url}`
}

const fetchUserInfo = async () => {
  try {
    loading.value = true
    const response = await request({
      url: `/users/detail/${route.params.id}`,
      method: 'get'
    })
    // 处理图片 URL
    if (response.data.photo_urls) {
      response.data.photo_urls = response.data.photo_urls.map(getFullImageUrl)
    }
    userInfo.value = response.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
    if (error.response?.data?.message) {
      showToast(error.response.data.message)
    } else if (error.message) {
      showToast(error.message)
    } else {
      showToast('获取用户信息失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 预览图片
const previewImage = (startPosition) => {
  showImagePreview({
    images: userInfo.value.photo_urls,
    startPosition,
    showIndex: true,
    closeOnPopstate: true,
    maxZoom: 3,
    minZoom: 1/3,
  })
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style>
:root {
  --van-cell-group-inset-padding: 12px;
  --van-cell-group-inset-border-radius: 8px;
  --van-cell-label-width: 6em;
}

.photo-container {
  margin: -16px;
  padding: 16px;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  padding: 8px 0;
}

.photo-item {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.photo-item :deep(.van-image) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 修改 van-cell 的样式以适应图片 */
:deep(.van-cell) {
  align-items: flex-start;
}

:deep(.van-cell__value) {
  flex: 1;
  margin: 0;
  overflow: visible;
}

:deep(.van-cell__title) {
  flex-shrink: 0;
  min-width: 6em;
}

.pb-safe {
  padding-bottom: calc(constant(safe-area-inset-bottom) + 20px);
  padding-bottom: calc(env(safe-area-inset-bottom) + 20px);
}
</style> 